package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.exception.ApiException;
import com.ytjj.qmyx.admin.dao.ProductSubjectPlateDao;
import com.ytjj.qmyx.admin.dao.SubjectPlateDao;
import com.ytjj.qmyx.admin.dao.SubjectsDao;
import com.ytjj.qmyx.admin.model.request.ProductSubjectPlateRequest;
import com.ytjj.qmyx.admin.model.request.SubjectsRequest;
import com.ytjj.qmyx.admin.model.response.ProductSubjectPlateResponse;
import com.ytjj.qmyx.admin.model.response.SubjectPlateResponse;
import com.ytjj.qmyx.admin.model.response.SubjectsResponse;
import com.ytjj.qmyx.admin.service.SubjectsService;
import com.ytjj.qmyx.mall.mapper.ProductSubjectPlateMapper;
import com.ytjj.qmyx.mall.mapper.SubjectPlateMapper;
import com.ytjj.qmyx.mall.mapper.SubjectsMapper;
import com.ytjj.qmyx.mall.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *
 * 
 * @description:
 */
@Service
public class SubjectsServiceImpl implements SubjectsService {

    @Autowired
    private SubjectsMapper subjectsMapper;

    @Autowired
    private SubjectsDao subjectsDao;

    @Autowired
    private SubjectPlateMapper subjectPlateMapper;

    @Autowired
    private SubjectPlateDao subjectPlateDao;

    @Autowired
    private ProductSubjectPlateDao productSubjectPlateDao;

    @Autowired
    private ProductSubjectPlateMapper productSubjectPlateMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addOrEditSubject(SubjectsRequest subjectsRequest) {
        String errorMsg = "操作失败";
        try {
            List<SubjectPlate> subjectPlates = subjectsRequest.getSubjectPlates();
            if (StringUtils.isEmpty(subjectsRequest.getTitle())) {
                errorMsg = "专题标题不能为空";
                throw new Exception();
            }
            if (subjectsRequest.getSubjectPlates() == null || subjectsRequest.getSubjectPlates().size() == 0) {
                errorMsg = "至少有一个板块";
                throw new Exception();
            }
            if (subjectsRequest.getId() != null && subjectsRequest.getId() != 0) {//修改
                //1.修改专题信息
                subjectsMapper.updateByPrimaryKeySelective(subjectsRequest);
                //2.修改/新增板块数据
                for (SubjectPlate subjectPlate : subjectPlates) {
                    if (StringUtils.isEmpty(subjectPlate.getTitle())) {
                        errorMsg = "板块名称不能为空";
                        throw new Exception();
                    }
                    if (subjectPlate.getId() != null && subjectPlate.getId() != 0) {//2.1修改
                        subjectPlateMapper.updateByPrimaryKeySelective(subjectPlate);
                    } else {//2.1新增
                        subjectPlate.setSubjectId(subjectsRequest.getId());
                        subjectPlateMapper.insertSelective(subjectPlate);
                    }
                }
                List<Integer> ids = Optional.ofNullable(subjectsRequest.getSubjectPlates()).map(s -> s.stream().map(e -> e.getId()).collect(Collectors.toList())).get();
                //2.2删除板块
                subjectPlateDao.delSubjectPlate(ids, subjectsRequest.getId());
                //2.2删除专题、板块关联的商品
                productSubjectPlateDao.delProductSubjectPlate(ids, subjectsRequest.getId());
            } else {//新增
                //1.新增专题数据
                subjectsMapper.insertSelective(subjectsRequest);
                //2.新增板块数据
                for (SubjectPlate subjectPlate : subjectPlates) {
                    if (StringUtils.isEmpty(subjectPlate.getTitle())) {
                        errorMsg = "板块名称不能为空";
                        throw new Exception();
                    }
                    subjectPlate.setSubjectId(subjectsRequest.getId());
                    subjectPlateMapper.insertSelective(subjectPlate);
                }
            }
        } catch (Exception e) {
            throw new ApiException(errorMsg);
        }
        return true;
    }

    @Override
    public CommonPage<SubjectsResponse> getSubject(SubjectsRequest subjectsRequest) {
        PageHelper.startPage(subjectsRequest.getPageNum(),subjectsRequest.getPageSize());
        List<SubjectsResponse> subject = subjectsDao.getSubject(subjectsRequest);
        return CommonPage.restPage(subject);
    }

    @Override
    public CommonPage<SubjectPlateResponse> getPlateBySubjectId(Integer subjectId) {
//        PageHelper.startPage(new SubjectPlateRequest().getPageNum(),new SubjectPlateRequest().getPageSize());
        List<SubjectPlateResponse> plateInfo = subjectPlateDao.getPlateBySubjectId(subjectId);
        return CommonPage.restPage(plateInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delSubjectById(Integer id) {
        try {
            //1.删除专题
            Subjects subjects = new Subjects();
            subjects.setId(id);
            subjects.setIsDeleted(1);
            subjectsMapper.updateByPrimaryKeySelective(subjects);
            //2.删除板块及商品
            this.delPlateBySubjectId(id);
        } catch (Exception e) {
            throw new ApiException("删除失败");
        }
        return true;
    }

    @Override
    public Map<String,Object> addProduct(ProductSubjectPlate productSubjectPlate) {
        int count = 0;
        if(productSubjectPlate.getProductId() == null){
            throw new ApiException("商品id不存在");
        }
        if(productSubjectPlate.getPercentage() != null && productSubjectPlate.getPercentage().compareTo(BigDecimal.valueOf(100)) == 1){
            throw new ApiException("抢占比不能大于100");
        }
        if(productSubjectPlate.getId() == null){//新增
            //1.商品是否已存在
            ProductSubjectPlateExample productSubjectPlateExample = new ProductSubjectPlateExample();
            productSubjectPlateExample.createCriteria().andProductIdEqualTo(productSubjectPlate.getProductId()).andIsDeletedEqualTo(0);
//            List<ProductSubjectPlate> productSubjectPlates = productSubjectPlateMapper.selectByExample(productSubjectPlateExample);
//            if(productSubjectPlates.size()>0){
//                throw new ApiException("商品已存在");
//            }
            count = productSubjectPlateMapper.insertSelective(productSubjectPlate);
        }else{//修改
            count = productSubjectPlateMapper.updateByPrimaryKeySelective(productSubjectPlate);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("result",count > 0 ? true : false);
        map.put("id",count > 0 ? productSubjectPlate.getId() : 0);
        return map;
    }

    @Override
    public CommonPage<ProductSubjectPlateResponse> getProductByPlateId(ProductSubjectPlateRequest productSubjectPlateRequest) {
        PageHelper.startPage(productSubjectPlateRequest.getPageNum(),productSubjectPlateRequest.getPageSize());
        List<ProductSubjectPlateResponse> productByPlateId = productSubjectPlateDao.getProductByPlateId(productSubjectPlateRequest.getPlateId());
        return CommonPage.restPage(productByPlateId);
    }

    @Override
    public SubjectsResponse getSubjectInfo(Integer id) {
        SubjectsResponse subjectsResponse = new SubjectsResponse();
        //1.获得专题
        Subjects subjects = subjectsMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(subjects,subjectsResponse);

        //2.根据专题获得板块
        SubjectPlateExample subjectPlateExample = new SubjectPlateExample();
        subjectPlateExample.createCriteria().andSubjectIdEqualTo(id).andIsDeletedEqualTo(0);
        List<SubjectPlate> subjectPlates = subjectPlateMapper.selectByExample(subjectPlateExample);
        subjectsResponse.setSubjectPlates(subjectPlates);
        return subjectsResponse;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delPlateBySubjectId(Integer subjectId) {
        try {
            SubjectPlateExample subjectPlateExample = new SubjectPlateExample();
            subjectPlateExample.createCriteria().andSubjectIdEqualTo(subjectId).andIsDeletedEqualTo(0);
            List<SubjectPlate> subjectPlates = subjectPlateMapper.selectByExample(subjectPlateExample);
            subjectPlates.stream().forEach(e->{
                this.delPlateById(e.getId());
            });
        } catch (Exception e) {
            throw new ApiException("删除板块出错");
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delPlateById(Integer id) {
        //1.判断板块数量，等于1时不能删除
        SubjectPlate subjectPlateEntity = subjectPlateMapper.selectByPrimaryKey(id);
        //1.1 当前专题的Id
        Integer subjectId = Optional.ofNullable(subjectPlateEntity).orElseThrow(() -> new ApiException("板块不存在")).getSubjectId();
        //1.2 专题下板块的数量
        SubjectPlateExample subjectPlateExample = new SubjectPlateExample();
        subjectPlateExample.createCriteria().andIsDeletedEqualTo(0).andSubjectIdEqualTo(subjectId);
        long count = subjectPlateMapper.countByExample(subjectPlateExample);
        if (count == 1) {
            throw new ApiException("删除失败，至少有一个板块");
        }

        try {
            //2.删除板块
            SubjectPlate subjectPlate = new SubjectPlate();
            subjectPlate.setId(id);
            subjectPlate.setIsDeleted(1);
            subjectPlateMapper.updateByPrimaryKeySelective(subjectPlate);

            //3.删除商品
            ProductSubjectPlateExample productSubjectPlateExample = new ProductSubjectPlateExample();
            productSubjectPlateExample.createCriteria().andPlateIdEqualTo(id).andIsDeletedEqualTo(0);
            List<ProductSubjectPlate> productSubjectPlates = productSubjectPlateMapper.selectByExample(productSubjectPlateExample);
            productSubjectPlates.stream().forEach(ps -> {
                this.delProductById(ps.getId());
            });
        } catch (Exception e) {
            e.getStackTrace();
            throw new ApiException("删除板块出错");
        }
        return true;
    }

    @Override
    public boolean delProductById(Integer id){
        ProductSubjectPlate productSubjectPlate = new ProductSubjectPlate();
        productSubjectPlate.setId(id);
        productSubjectPlate.setIsDeleted(1);
        int i = productSubjectPlateMapper.updateByPrimaryKeySelective(productSubjectPlate);
        return i > 0 ? true : false;
    }

    @Override
    public ProductSubjectPlateResponse getProductEditInfo(Integer id) {
        ProductSubjectPlateResponse productEditInfo = productSubjectPlateDao.getProductEditInfo(id);
        return productEditInfo;
    }
}
